package com.choudou5.solr.util;

import cn.hutool.core.util.ArrayUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

public class IpUtil {

    private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "X-Real-IP",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"};
    /**
     * 获取真实IP地址 （nginx配置 http://www.nginx.cn/4646.html）
     * @param req
     * @return
     */
    public static String getRealIpAddr(HttpServletRequest req) {
        String ip = null;
        loop1: for (String header : HEADERS_TO_TRY) {
            ip = req.getHeader(header);
            if (StrUtil.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                String[] ips = StrUtil.splitToArray(ip, ',');
                if(ArrayUtil.isNotEmpty(ips)){
                    loop2: for(String tmpip : ips){
                        if(StrUtil.isBlank(tmpip))
                            continue loop2;
                        tmpip = tmpip.trim();
                        //排除 局域网
                        if(isIpAddr(tmpip) && !tmpip.startsWith("10.") && !tmpip.startsWith("192.168.") && !"127.0.0.1".equals(tmpip)){
                            ip = tmpip.trim();
                            break loop1;
                        }
                    }
                }
            }
        }
        if(StrUtil.isBlank(ip)){
            ip = req.getRemoteAddr();
            LogDeBugUtil.debug("remoteAddr ip:" + ip);
            if(ip.indexOf('.')==-1)
                ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 判断字符串是否是一个IP地址
     * @param addr
     * @return
     */
    public static boolean isIpAddr(String addr){
        if(StrUtil.isEmpty(addr))
            return false;
        String[] ips = StrUtil.splitToArray(addr, '.');
        if(ips.length != 4)
            return false;
        try{
            int ipa = Integer.parseInt(ips[0]);
            int ipb = Integer.parseInt(ips[1]);
            int ipc = Integer.parseInt(ips[2]);
            int ipd = Integer.parseInt(ips[3]);
            return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0
                    && ipc <= 255 && ipd >= 0 && ipd <= 255;
        }catch(Exception e){

        }
        return false;
    }

    
    /** 
     * 获取本机的IP 
     * @return Ip地址 
     */ 
     public static String getLocalHostIP() { 
          String ip; 
          try {
               InetAddress addr = InetAddress.getLocalHost();
               ip = addr.getHostAddress();  
          } catch(Exception ex) {
              ip = ""; 
          } 
            
          return ip; 
     }
     
     /** 
      * 获取 服务器端口 
      * @param request 
      * @return 
      */  
     public static int getLocalPort(HttpServletRequest request){  
         return request.getLocalPort();
     }
     
     /** 
      * 或者主机名： 
      * @return 
      */ 
     public static String getLocalHostName() { 
          String hostName; 
          try { 
               InetAddress addr = InetAddress.getLocalHost(); 
               /**获取此 IP 地址的主机名。*/ 
               hostName = addr.getHostName(); 
          }catch(Exception ex){ 
              hostName = ""; 
          } 
          return hostName; 
     } 
     
     /** 
      * 获得本地所有的IP地址 
      * @return 
      */ 
     public static String[] getAllLocalHostIP() { 
         String[] ret = null; 
          try { 
               String hostName = getLocalHostName(); 
               if(hostName.length()>0) { 
                   /**在给定主机名的情况下，根据系统上配置的名称服务返回其 IP 地址所组成的数组。*/ 
                    InetAddress[] addrs = InetAddress.getAllByName(hostName); 
                    if(addrs.length>0) { 
                         ret = new String[addrs.length]; 
                         for(int i=0 ; i< addrs.length ; i++) { 
                             /**.getHostAddress()   返回 IP 地址字符串（以文本表现形式）。*/ 
                             ret[i] = addrs[i].getHostAddress(); 
                         } 
                    } 
               } 
          }catch(Exception ex) { 
              ret = null; 
          } 
          return ret; 
     } 
     
     public static void main(String[] args) throws Exception { 
         System.out.println("本机IP：" + getLocalHostIP()); 
         System.out.println("本地主机名字为：" + getLocalHostName()); 
         String[] localIP = getAllLocalHostIP(); 
         for (int i = 0; i < localIP.length; i++) { 
             System.out.println(localIP[i]); 
         } 
          
         InetAddress baidu = InetAddress.getByName("www.baidu.com");
         System.out.println("baidu : " + baidu);
         System.out.println("baidu IP: " + baidu.getHostAddress());
         System.out.println("baidu HostName: " + baidu.getHostName());
     }


}
